﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _2.GenericList
{
    class GenericList<T>
    {
        private T[] arr;
        private int count;
        private int INITIAL_CAPACITY = 4;
        public int Count
        {
            get { return count; }
        }
        public GenericList(int list)
        {
            INITIAL_CAPACITY = list;
            arr = new T[INITIAL_CAPACITY];
            count = 0;
        }
        public void Add(T item)
        {
            Insert(count, item);
        }
        public void Insert(int index, T item)
        {
            if (index > count || index < 0)
            {
                throw new IndexOutOfRangeException("Invalid index: " + index);
            }
            T[] extendedArr = arr;
            if (count + 1 == arr.Length)
            {
                extendedArr = new T[arr.Length * 2];
            }
            Array.Copy(arr, extendedArr, index);
            count++;
            Array.Copy(arr, index, extendedArr, index + 1, count - index - 1);
            extendedArr[index] = item;
            arr = extendedArr;
        }
        public void Clear()
        {
            arr = new T[INITIAL_CAPACITY];
            count = 0;
        }
        public T this[int index]
        {
            get
            {
                if (index >= count || index < 0)
                {
                    throw new ArgumentOutOfRangeException("Invalid index: " + index);
                }
                return arr[index];
            }
            set
            {
                if (index >= count || index < 0)
                {
                    throw new ArgumentOutOfRangeException("Invalid index: " + index);
                }
                arr[index] = value;
            }
        }
        public int IndexOf(T item)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                if (item.Equals(arr[i]) == true)
                {
                    return i;
                }
            }
            return -1;
        }
        public void Remove(int index)
        {
            if (index >= count || index < 0)
            {
                throw new ArgumentOutOfRangeException(
                      "Invalid index: " + index);
            }
            Array.Copy(arr, index + 1, arr, index, count - index + 1);
            count--;
        }
        public override string ToString()
        {
            StringBuilder text = new StringBuilder();
            for (int i = 0; i < count; i++)
            {
                text.Append(arr[i] + " ");
            }
            return text.ToString();
        }
    }
}
